package chapter14;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/22 19:19
 */
public class JsonTest {
    public static void main(String[] args) {
        Student student = new Student("张三", 18, 90.8);
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        try {
            String str = mapper.writeValueAsString(student);
            System.out.println(str);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        ObjectMapper xmlMapper = new XmlMapper();
        xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
        try {
            String xml = xmlMapper.writeValueAsString(student);
            System.out.println(xml);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        /*ObjectMapper datapackMapper = new ObjectMapper(new MessagePackFactory());
        try {
            byte[] bytes = datapackMapper.writeValueAsBytes(student);
            datapackMapper.writeValue(new File("D:\\student.bson"), bytes);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        List<Student> students = Arrays.asList(new Student[]{new Student("zhangsan", 18, 98.1), new Student("lisi", 15, 76.2)});
        String json = null;
        try {
            json = mapper.writeValueAsString(students);
            System.out.println("list json" + json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        try {
            List<Student> deserilizeJson = mapper.readValue(json, new TypeReference<List<Student>>() {
            });
            System.out.println("deserilize json " + deserilizeJson);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
